package com.zahb.qadx.webview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;

import com.githang.statusbar.StatusBarCompat;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.net.RetrofitStudyTimeService;
import com.zahb.qadx.util.CompatHelper;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MyWebViewActivity extends BaseActivity {

    private static final String TAG = MyWebViewActivity.class.getSimpleName();

    private WebView mWebView;
    private ProgressBar mProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        initData();
        mWebView.addJavascriptInterface(new MyJavascriptInterface(getContext(), () -> {
            int from = getIntent().getIntExtra("from", -1);
            if (from == 1) {// 课程目录，考试列表等可以直接返回的页面
                finish();
            }
        }), "androidApi");
        //setTitleText(getIntent().getStringExtra("title") + "");
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#4c87ff"));
        String url = getIntent().getStringExtra("url");
//        Map<String, String> extraHeaders = new HashMap<String, String>();
//        extraHeaders.put("Referer", "123");
        Log.e("url",url);
        mWebView.loadUrl(url + "");
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_web_view;
    }

    @Override
    protected void initViews() {
        mWebView = findViewById(R.id.web_view);
        mProgressBar = findViewById(R.id.progress_bar);
        mProgressBar.setMax(100);
    }

    @Override
    protected int getTitleStringRes() {
        return 0;
    }

    public static void actionStart(Context context, String url, String title, int from) {
        actionStart(context, url, title, from, "");
    }

    public static void actionStart(Context context, String url, String title, int from, String json) {
        Intent intent = new Intent(context, MyWebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        intent.putExtra("from", from);
        intent.putExtra("json", json);
        context.startActivity(intent);
    }

    public static void actionStart(Context context, String url, String title) {
        actionStart(context, url, title, -1);
    }

    public void saveStudyTime() {
        String json = getIntent().getStringExtra("json");
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), json);
        RetrofitStudyTimeService.sCollectionType = RetrofitStudyTimeService.sCollectionTypePractice;
        Disposable disposable = RetrofitStudyTimeService.getNetService().saveStudyTime(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {

                }, Throwable::printStackTrace);
        addDisposable(disposable);
    }

    @Override
    protected void setTitleText(@NonNull String title) {
        super.setTitleText(title);
        mTopBarDivider.setVisibility(CompatHelper.isEmpty(title) ? View.GONE : View.VISIBLE);
    }

    private void initData() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setTextZoom(100);//设置H5页面中字体大小不跟随手机系统

        if (Build.VERSION.SDK_INT >= 19) {
            //webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//加载缓存否则网络
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不加载缓存
        }

        if (Build.VERSION.SDK_INT >= 19) {
            webSettings.setLoadsImagesAutomatically(true);//图片自动缩放 打开
        } else {
            webSettings.setLoadsImagesAutomatically(false);//图片自动缩放 关闭
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);//软件解码
        }
        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);//硬件解码

        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本
        webSettings.setSupportZoom(true);// 设置可以支持缩放
        webSettings.setBuiltInZoomControls(true);// 设置出现缩放工具 是否使用WebView内置的缩放组件，由浮动在窗口上的缩放控制和手势缩放控制组成，默认false

        webSettings.setDisplayZoomControls(false);//隐藏缩放工具
        webSettings.setUseWideViewPort(true);// 扩大比例的缩放

        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//自适应屏幕
        webSettings.setLoadWithOverviewMode(true);

        webSettings.setDatabaseEnabled(true);//
        webSettings.setSavePassword(true);//保存密码
        webSettings.setDomStorageEnabled(true);//是否开启本地DOM存储  鉴于它的安全特性（任何人都能读取到它，尽管有相应的限制，将敏感数据存储在这里依然不是明智之举），Android 默认是关闭该功能的。
        mWebView.setSaveEnabled(true);
        mWebView.setKeepScreenOn(true);

        // 设置setWebChromeClient对象
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                //setTitleText(title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                    mProgressBar.setProgress(newProgress, true);
                else
                    mProgressBar.setProgress(newProgress);
            }
        });

        //设置此方法可在WebView中打开链接，反之用浏览器打开
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!mWebView.getSettings().getLoadsImagesAutomatically()) {
                    mWebView.getSettings().setLoadsImagesAutomatically(true);
                }
                mProgressBar.setVisibility(View.GONE);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                mProgressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                    return false;
                }

                // Otherwise allow the OS to handle things like tel, mailto, etc.
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        });

        mWebView.setDownloadListener((paramAnonymousString1, paramAnonymousString2, paramAnonymousString3, paramAnonymousString4, paramAnonymousLong) -> {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            intent.setData(Uri.parse(paramAnonymousString1));
            startActivity(intent);
        });
    }

    @Override
    public void onBackPressed() {
        String currentUrl = mWebView.getUrl();
        Log.d(TAG, "currentUrl: " + currentUrl);
        if (currentUrl != null && currentUrl.contains("?")) {
            String baseUrl = currentUrl.split("\\?")[0];
            if (baseUrl.endsWith("exam/examQuestion")) {
                showBindToast("考试过程中，禁止返回");
                return;
            }
        }
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}
